package io.bdmc.modules.api.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import io.bdmc.common.exception.RRException;
import io.bdmc.common.utils.R;
import io.bdmc.common.utils.WebTokenUtil;
import io.bdmc.modules.api.annotation.AuthIgnore;
import io.bdmc.modules.api.model.LoginInfo;

/**
 * 权限(Token)验证
 * 
 * @author huang lu
 * @email hlkyo@qq.com
 * @date 2017-03-23 15:38
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    public static final Logger logger = LoggerFactory.getLogger((AuthorizationInterceptor.class));
    public static final String USER_KEY = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        AuthIgnore annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthIgnore.class);
        } else {
            return true;
        }

        // 如果有@IgnoreAuth注解，则不验证token
        if (annotation != null) {
            return true;
        }

        // 从header中获取token
        String token = request.getHeader("token");
        // 如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }

        // token为空
        if (StringUtils.isBlank(token)) {
            throw new RRException("token不能为空");
        }

        // //查询token信息
        // TokenEntity tokenEntity = tokenService.queryByToken(token);
        // if(tokenEntity == null || tokenEntity.getExpireTime().getTime() <
        // System.currentTimeMillis()){
        // throw new RRException("token失效，请重新登录");
        // }

        // 设置userId到request里，后续根据userId，获取用户信息
        // request.setAttribute(USER_KEY, tokenEntity.getUserId());
        boolean handleResult = false;

        LoginInfo logininfo = WebTokenUtil.validateJWT(token);
        if (logininfo == null) {// fanhui 401
            PrintWriter writer = null;
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            try {
                writer = response.getWriter();
                R m = R.error("token信息有误");
                writer.print(JSONObject.toJSON(m));
                return handleResult;
            } catch (IOException e) {
                logger.error("response error", e);
            } finally {
                if (writer != null)
                    writer.close();
            }
        }

        request.setAttribute("user_id", logininfo.id);
        request.setAttribute("dep_id", logininfo.dep_id);
        request.setAttribute("loginName", logininfo.loginName);
        handleResult = true;
        return handleResult;
    }
}
